var net =require("net");
var files = require('fs').createWriteStream('./message.txt');

var server  = new net.createServer();

server.on("connection",function (socket) {
   console.log("C 和S 连接成功");
    socket.setEncoding('utf8');
    const address = socket.address();

    var iMsg ="";
    socket.on('data',function (data) {
        iMsg +=data;
        console.log("c连接到服务器的地址%j",address);
        console.log("服务器接收到客户端的数据",iMsg,address);
        socket.write(iMsg);

    });
    socket.pipe(files);  //写在外面只写一次

    socket.on('error',function (error) {
        console.log("和客户端通信过程中发生的错误，错误信息为%s",error.code);
        socket.destroy();
    });
    socket.ref();
    socket.on("end",function (error) {
        console.log("客户端主动断开了");
        socket.unref();
    });

});

server.getConnections(function (error, count) {
    if (error) throw err;
    console.log("当前客户端连接有%j个", count)
    server.maxConnections = 2;
    console.log("当前服务器最大支出连接数%j", server.maxConnections);
});
server.listen(8431,"localhost");

server.on('close',function (had_error) {
    if(had_error){
        console.log("由一个端口导致socket端口被关闭");
        socket.unref();
    }
    else
        console.log('socket端口被正常关闭');
});